package com.naodong.shenluntiku.mvp.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.loadmore.LoadMoreView;
import com.naodong.shenluntiku.R;
import com.naodong.shenluntiku.di.component.DaggerStudyComponent;
import com.naodong.shenluntiku.di.module.StudyModule;
import com.naodong.shenluntiku.mvp.contract.StudyContract;
import com.naodong.shenluntiku.mvp.model.bean.EventBusTag;
import com.naodong.shenluntiku.mvp.model.bean.OnceTipType;
import com.naodong.shenluntiku.mvp.model.bean.PagingBean;
import com.naodong.shenluntiku.mvp.model.bean.Study;
import com.naodong.shenluntiku.mvp.model.bean.StudyWrapper;
import com.naodong.shenluntiku.mvp.model.data.api.CommonApi;
import com.naodong.shenluntiku.mvp.model.data.manager.BoxManager;
import com.naodong.shenluntiku.mvp.presenter.StudyPresenter;
import com.naodong.shenluntiku.mvp.view.activity.StudySetUpActivity;
import com.naodong.shenluntiku.mvp.view.adapter.StudyAdapter;
import com.naodong.shenluntiku.mvp.view.widget.TopTipViewManager;
import com.naodong.shenluntiku.util.AppUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.shingohu.man.base.BaseMVPFragment;
import me.shingohu.man.di.component.AppComponent;
import me.shingohu.man.model.bean.SimpleEvent;
import me.shingohu.man.util.UiUtils;
import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by hujie on 17/4/18.
 */

public class StudyFragment extends BaseMVPFragment<StudyPresenter> implements StudyContract.View, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;

    @BindView(R.id.contentView)
    LinearLayout contentView;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    StudyAdapter mAdapter;

    String moreUrl;

    @BindView(R.id.setView)
    View setView;

    TopTipViewManager topTipViewManager;


    public static SupportFragment getInstance() {
        return new StudyFragment();
    }


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerStudyComponent.builder().appComponent(appComponent).studyModule(new StudyModule(this)).build().inject(this);
    }

    @Override
    protected void onViewCreated(Bundle savedInstanceState) {
        swipeRefreshLayout.setOnRefreshListener(this);
    }


    @OnClick(R.id.menuView)
    public void onSetClick() {
        Intent intent = new Intent(mActivity, StudySetUpActivity.class);
        startActivity(intent);
    }


    @Override
    protected int layoutId() {
        return R.layout.f_study;
    }

    @Override
    public void showMessage(String msg) {

    }


    @Override
    public void onRequesrStart() {
        swipeRefreshLayout.setRefreshing(true);
    }

    @Override
    public void onRequestFinish() {
        swipeRefreshLayout.setRefreshing(false);
        if (mAdapter != null && mAdapter.isLoading()) {
            mAdapter.loadMoreComplete();
        }
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        firstRequest();
    }

    @Override
    public void setStudyListData(boolean isRefresh, PagingBean<List<Study>> listPagingBean) {
        if (mAdapter == null) {
            initRecycleView();
        }
        if (isRefresh) {
            firstShowTipView();
            mAdapter.setNewData(wrapperData(listPagingBean.getData()));
        } else {
            if (listPagingBean.getData() != null && listPagingBean.getData().size() > 0) {
                mAdapter.addData(wrapperData(listPagingBean.getData()));
            }
        }
        checkHasMore(listPagingBean);
    }

    @Override
    public void onReadSuccess(int rcId) {
        updateCompletNumById(rcId);
    }

    /**
     * 更新完成数量
     * @param rcId
     */
    private void updateCompletNumById(int rcId) {
        if (mAdapter != null) {
            StudyWrapper psw = null;//父类psw
            for (int i = 0; i < mAdapter.getData().size(); i++) {
                StudyWrapper sw = mAdapter.getItem(i);
                if (sw != null) {
                    if (sw.getItem() == null) {
                        psw = sw;
                    } else {
                        if (sw.getItem().getRcId() == rcId && psw != null && !sw.getItem().isFinish()) {
                            //找到了需要更新的
                            sw.getItem().setIsFinish(true);
                            psw.setDprTaskCompleteNum(psw.getDprTaskCompleteNum() + 1);
                            mAdapter.notifyDataSetChanged();
                            return;
                        }
                    }
                }
            }
        }
    }

    private void checkHasMore(PagingBean pagingBean) {
        moreUrl = pagingBean.getNextUrl();
        if (moreUrl != null) {
            mAdapter.setEnableLoadMore(true);
            mAdapter.loadMoreComplete();
        } else {
            mAdapter.loadMoreEnd();
        }
    }

    private List<StudyWrapper> wrapperData(List<Study> studies) {
        List<StudyWrapper> studyWrappers = new ArrayList<>();
        for (Study study : studies) {
            StudyWrapper studyWrapper = new StudyWrapper(StudyWrapper.TITLE, study.getDprId(), study.getDprTitle(), study.getDprTaskNum(), study.getDprTaskCompleteNum(), study.getDrTaskCompleteNum(), study.getDrAssessCompleteNum());
            studyWrappers.add(studyWrapper);


            if (study.getRecContents() != null && study.getRecContents().size() > 0) {
                for (Study.Content content : study.getRecContents()) {
                    StudyWrapper studyWrapper1 = null;
                    if (content.getRecommendType().equals("rec_choice_subject")) {
                        studyWrapper1 = new StudyWrapper(StudyWrapper.QUICK_START, content);
                        studyWrapper1.setDrAssessCompleteNum(studyWrapper.getDrAssessCompleteNum());
                    } else if (content.getRecommendType().equals("rec_video")) {
                        studyWrapper1 = new StudyWrapper(StudyWrapper.VIDEO, content);
                    } else {
                        studyWrapper1 = new StudyWrapper(StudyWrapper.SUBJECT, content);
                    }
                    studyWrappers.add(studyWrapper1);
                }
            }
        }
        return studyWrappers;
    }

    private void initRecycleView() {

        UiUtils.configRecycleView(recyclerView, new LinearLayoutManager(getActivity()));
        mAdapter = new StudyAdapter(mPresenter);
        mAdapter.bindToRecyclerView(recyclerView);
        mAdapter.setLoadMoreView(new CustomLoadMoreView());


        mAdapter.setOnLoadMoreListener(() -> {
            if (moreUrl != null) {
                mPresenter.requesStudyList(false, moreUrl);
            } else {
                mAdapter.loadMoreEnd();
            }
        }, recyclerView);

    }

    private void firstRequest() {
        if (mPresenter != null) {
            String url = CommonApi.APP_URL + "api/userRec";
            mPresenter.requesStudyList(true, url);
        }
    }


    @Override
    protected boolean userEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SimpleEvent event) {
        if (event.getType() == EventBusTag.NOTIFY_STUDYFRAGMENT_REFRESH) {
            recyclerView.postDelayed(this::firstRequest, 100);
        } else if (event.getType() == EventBusTag.NOTIFY_STUDYFRAGMENT_UPDATE_DATA) {
            updateCompletNumById(event.getIntEvent());
        } else if (event.getType() == EventBusTag.NOTIFY_STUDY_SHOW_TIP_VIEW) {
            if (topTipViewManager == null) {
                topTipViewManager = new TopTipViewManager(contentView);
            }
            topTipViewManager.showTipView(event.getStrEvent());
        }
    }

    @Override
    public void onRefresh() {
        firstRequest();
    }


    @Override
    public void onDestroy() {
        if (topTipViewManager != null) {
            topTipViewManager.destory();
        }
        super.onDestroy();
    }


    /**
     * 第一次弹出一个提示对话框
     */
    private synchronized void firstShowTipView() {

        if (!BoxManager.getInstance().queryBoxOnceStatusByType(OnceTipType.study_dialog_tip)) {
            BoxManager.getInstance().putBoxOnce(OnceTipType.study_dialog_tip, true);
            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity, R.style.Dialog);
            View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_study_tip, null);
            builder.setView(view);
            AlertDialog dialog = builder.show();
            view.findViewById(R.id.sureBtn).setOnClickListener(v -> {
                dialog.dismiss();
            });
        }
    }

    class CustomLoadMoreView extends LoadMoreView {

        @Override
        public int getLayoutId() {
            return R.layout.custom_load_more_view;
        }

        @Override
        protected int getLoadingViewId() {
            return R.id.load_more_loading_view;
        }

        @Override
        protected int getLoadFailViewId() {
            return R.id.load_more_load_fail_view;
        }

        @Override
        protected int getLoadEndViewId() {
            return R.id.load_more_load_end_view;
        }

        @Override
        public void convert(BaseViewHolder holder) {
            super.convert(holder);

            View endView = holder.getView(getLoadEndViewId());
            if (endView != null) {
                endView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!BoxManager.getInstance().queryBoxOnceStatusByType(OnceTipType.study_set_tip)) {
                            BoxManager.getInstance().putBoxOnce(OnceTipType.study_set_tip, true);
                            AppUtil.startOnceTipActivity(mActivity, OnceTipType.study_set_tip, setView);
                        } else {
                            onSetClick();
                        }
                    }
                });
            }

        }
    }


}
